<template>
  <div>
    <!-- Sidebar -->
    <div class="sidebar">
      <div style="padding: 24px 20px; border-bottom: 1px solid #e5e7eb;">
        <div style="display: flex; align-items: center;">
          <div style="width: 40px; height: 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 18px;">快</div>
          <div style="margin-left: 12px;">
            <div style="font-weight: 600; color: #111827;">快递代拿管理系统</div>
          </div>
        </div>
      </div>

      <div style="padding: 16px 0;">
        <div class="nav-section">主菜单</div>
        <button :class="['nav-item', $route.path === '/admin/dashboard' ? 'active' : '']" @click="$router.push('/admin/dashboard')"><i class="fas fa-chart-line"></i><span>数据总览</span></button>
        <button :class="['nav-item', $route.path === '/admin/orders' ? 'active' : '']" @click="$router.push('/admin/orders')"><i class="fas fa-box"></i><span>订单管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/users' ? 'active' : '']" @click="$router.push('/admin/users')"><i class="fas fa-users"></i><span>下单者管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/couriers' ? 'active' : '']" @click="$router.push('/admin/couriers')"><i class="fas fa-motorcycle"></i><span>代拿者管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/finance' ? 'active' : '']" @click="$router.push('/admin/finance')"><i class="fas fa-wallet"></i><span>财务管理</span></button>

        <div class="nav-section">运营管理</div>
        <button :class="['nav-item', $route.path === '/admin/announcements' ? 'active' : '']" @click="$router.push('/admin/announcements')"><i class="fas fa-bullhorn"></i><span>公告管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/pricing' ? 'active' : '']" @click="$router.push('/admin/pricing')"><i class="fas fa-percentage"></i><span>盈利规则</span></button>

        <div class="nav-section">系统设置</div>
        <button :class="['nav-item', $route.path === '/admin/permissions' ? 'active' : '']" @click="$router.push('/admin/permissions')"><i class="fas fa-shield-alt"></i><span>权限管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/logs' ? 'active' : '']" @click="$router.push('/admin/logs')"><i class="fas fa-file-alt"></i><span>系统日志</span></button>
        <button :class="['nav-item', $route.path === '/admin/settings' ? 'active' : '']" @click="$router.push('/admin/settings')"><i class="fas fa-cog"></i><span>系统设置</span></button>
      </div>

      <div style="position: absolute; bottom: 0; left: 0; right: 0; padding: 20px; border-top: 1px solid #e5e7eb;">
        <div style="display: flex; align-items: center;">
          <div style="width: 40px; height: 40px; border-radius: 50%; background:#e5e7eb; display:flex; align-items:center; justify-content:center; color:#6b7280; font-weight:600;">管</div>
          <div style="margin-left: 12px; flex: 1;">
            <div style="font-weight: 500; color: #111827; font-size: 14px;">管理员</div>
            <div style="font-size: 12px; color: #9ca3af;">超级管理员</div>
          </div>
        </div>
        <button class="nav-item" @click="confirmLogout" style="margin-top:12px;"><i class="fas fa-sign-out-alt"></i><span>退出登录</span></button>
      </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
      <!-- Header -->
      <div style="background: white; border-bottom: 1px solid #e5e7eb; padding: 16px 32px; display: flex; align-items: center; justify-content: space-between;">
        <div></div>
        <div style="position: relative;">
          <i class="fas fa-search" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #9ca3af;"></i>
          <input type="text" placeholder="搜索..." style="padding: 8px 12px 8px 36px; border: 1px solid #e5e7eb; border-radius: 8px; width: 240px; font-size: 14px;">
        </div>
      </div>

      <!-- Content -->
      <div style="padding: 32px;">
        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 32px;">
          <div>
            <h1 style="font-size: 28px; font-weight: 700; color: #111827; margin-bottom: 8px;">公告管理</h1>
            <p style="color: #6b7280;">发布和管理平台公告通知</p>
          </div>
          <button 
            @click="openCreateDialog"
            style="padding: 12px 24px; background: #3b82f6; color: white; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; font-size: 14px; font-weight: 500;"
          >
            <i class="fas fa-plus"></i>
            <span>发布公告</span>
          </button>
        </div>

        <!-- Announcements List -->
        <div class="content-card">
          <div v-if="loading" style="text-align: center; padding: 40px; color: #9ca3af;">加载中...</div>
          <div v-else-if="announcements.length === 0" style="text-align: center; padding: 40px; color: #9ca3af;">暂无公告</div>
          <div v-else>
            <div 
              v-for="ann in announcements" 
              :key="ann.id"
              class="announcement-card"
            >
              <div style="display:flex; align-items:start; justify-content: space-between; margin-bottom:12px;">
                <div style="flex:1;">
                  <div style="display:flex; align-items:center; gap:12px; margin-bottom:8px; flex-wrap: wrap;">
                    <h3 style="font-size:18px; font-weight:600; color:#111827;">{{ ann.title }}</h3>
                    <span v-if="ann.is_published" class="status-badge status-published">已发布</span>
                    <span v-else class="status-badge status-draft">草稿</span>
                    <span v-if="ann.is_top" style="display:inline-flex; align-items:center; gap:4px; font-size:12px; color:#ef4444;"><i class="fas fa-fire"></i>置顶</span>
                    <span 
                      :style="{
                        display: 'inline-flex',
                        alignItems: 'center',
                        gap: '4px',
                        fontSize: '12px',
                        padding: '4px 8px',
                        borderRadius: '12px',
                        background: ann.type === 'system' ? '#dbeafe' : ann.type === 'activity' ? '#fef3c7' : '#f3f4f6',
                        color: ann.type === 'system' ? '#1e40af' : ann.type === 'activity' ? '#92400e' : '#6b7280'
                      }"
                    >
                      {{ ann.type === 'system' ? '系统' : ann.type === 'activity' ? '活动' : '通知' }}
                    </span>
                  </div>
                  <p style="color:#6b7280; font-size:14px; line-height:1.6;">{{ ann.content.length > 100 ? ann.content.substring(0, 100) + '...' : ann.content }}</p>
                </div>
                <div style="display:flex; gap:8px; margin-left:16px;">
                  <button
                    @click="editAnnouncement(ann)"
                    style="padding:8px 14px; background:#f3f4f6; border:none; border-radius:999px; cursor:pointer; color:#374151; display:flex; align-items:center; gap:6px; font-size:12px;"
                    title="编辑公告"
                  >
                    <i class="fas fa-edit"></i>
                    <span>编辑</span>
                  </button>
                  <button
                    @click="deleteAnnouncement(ann.id)"
                    style="padding:8px 14px; background:#fee2e2; border:none; border-radius:999px; cursor:pointer; color:#dc2626; display:flex; align-items:center; gap:6px; font-size:12px;"
                    title="删除公告"
                  >
                    <i class="fas fa-trash"></i>
                    <span>删除</span>
                  </button>
                </div>
              </div>
              <div style="display:flex; align-items:center; gap:24px; font-size:13px; color:#9ca3af;">
                <span><i class="fas fa-user" style="margin-right:6px;"></i>{{ ann.creator_name || '管理员' }}</span>
                <span><i class="fas fa-clock" style="margin-right:6px;"></i>{{ formatDate(ann.published_at || ann.created_at) }}</span>
                <span><i class="fas fa-eye" style="margin-right:6px;"></i>{{ ann.view_count || 0 }} 次浏览</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 发布/编辑公告弹窗 -->
        <div v-if="showDialog" style="position:fixed; inset:0; background:rgba(0,0,0,.5); display:flex; align-items:center; justify-content:center; z-index:1000;">
          <div style="width: 700px; max-width: 90%; background:#fff; border-radius:12px; padding:24px; max-height: 90vh; overflow-y: auto;">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
              <h3 style="font-size:20px; font-weight:600;">{{ editingAnnouncement ? '编辑公告' : '发布公告' }}</h3>
              <button @click="closeDialog" style="border:0; background:transparent; font-size:24px; line-height:1; cursor:pointer; color:#6b7280;">×</button>
            </div>
            <div style="display:grid; gap:16px;">
              <div>
                <label style="display:block; font-size:14px; font-weight:500; color:#111827; margin-bottom:6px;">公告标题 <span style="color:#ef4444;">*</span></label>
                <input 
                  v-model="form.title" 
                  placeholder="请输入公告标题" 
                  style="width:100%; padding:10px 12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px;"
                />
              </div>
              <div>
                <label style="display:block; font-size:14px; font-weight:500; color:#111827; margin-bottom:6px;">公告内容 <span style="color:#ef4444;">*</span></label>
                <textarea 
                  v-model="form.content" 
                  rows="6"
                  placeholder="请输入公告内容" 
                  style="width:100%; padding:10px 12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px; resize:vertical;"
                ></textarea>
              </div>
              <div style="display:grid; grid-template-columns: 1fr 1fr; gap:12px;">
                <div>
                  <label style="display:block; font-size:14px; font-weight:500; color:#111827; margin-bottom:6px;">公告类型</label>
                  <select v-model="form.type" style="width:100%; padding:10px 12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px;">
                    <option value="notice">通知</option>
                    <option value="system">系统</option>
                    <option value="activity">活动</option>
                  </select>
                </div>
                <div>
                  <label style="display:block; font-size:14px; font-weight:500; color:#111827; margin-bottom:6px;">发布状态</label>
                  <select v-model.number="form.is_published" style="width:100%; padding:10px 12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px;">
                    <option :value="1">立即发布</option>
                    <option :value="0">保存为草稿</option>
                  </select>
                </div>
              </div>
              <div>
                <label style="display:flex; align-items:center; gap:8px; font-size:14px; color:#111827; cursor:pointer;">
                  <input type="checkbox" v-model.number="form.is_top" />
                  <span>置顶显示</span>
                </label>
              </div>
            </div>
            <div style="display:flex; justify-content:flex-end; gap:12px; margin-top:24px;">
              <button @click="closeDialog" style="padding: 10px 20px; background:#f3f4f6; color:#374151; border:0; border-radius:8px; cursor:pointer; font-size:14px; font-weight:500;">取消</button>
              <button @click="saveAnnouncement" style="padding: 10px 20px; background:#3b82f6; color:#fff; border:0; border-radius:8px; cursor:pointer; font-size:14px; font-weight:500;">{{ editingAnnouncement ? '保存修改' : '发布公告' }}</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'AdminAnnouncements',
  data() {
    return {
      announcements: [],
      loading: false,
      showDialog: false,
      editingAnnouncement: null,
      form: {
        title: '',
        content: '',
        type: 'notice',
        is_top: 0,
        is_published: 1
      }
    }
  },
  methods: {
    confirmLogout() {
      if (confirm('是否确认退出？')) {
        localStorage.removeItem('adminToken')
        localStorage.removeItem('adminInfo')
        localStorage.removeItem('userToken')
        this.$router.push('/login')
      }
    },
    formatDate(dateStr) {
      if (!dateStr) return '-'
      try {
        return new Date(dateStr).toLocaleString('zh-CN', { 
          year: 'numeric', 
          month: '2-digit', 
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      } catch {
        return dateStr
      }
    },
    async fetchAnnouncements() {
      this.loading = true
      try {
        const { data } = await axios.get('/api/admin/announcements')
        if (data && data.success) {
          this.announcements = data.data || []
        }
      } catch (e) {
        console.error('获取公告列表失败', e)
        ElMessage.error('获取公告列表失败')
      } finally {
        this.loading = false
      }
    },
    openCreateDialog() {
      this.editingAnnouncement = null
      this.form = {
        title: '',
        content: '',
        type: 'notice',
        is_top: 0,
        is_published: 1
      }
      this.showDialog = true
    },
    editAnnouncement(ann) {
      this.editingAnnouncement = ann
      this.form = {
        title: ann.title,
        content: ann.content,
        type: ann.type,
        is_top: ann.is_top ? 1 : 0,
        is_published: ann.is_published ? 1 : 0
      }
      this.showDialog = true
    },
    closeDialog() {
      this.showDialog = false
      this.editingAnnouncement = null
      this.form = {
        title: '',
        content: '',
        type: 'notice',
        is_top: 0,
        is_published: 1
      }
    },
    async saveAnnouncement() {
      if (!this.form.title || !this.form.content) {
        ElMessage.warning('请填写标题和内容')
        return
      }

      try {
        let response
        if (this.editingAnnouncement) {
          response = await axios.put(`/api/admin/announcements/${this.editingAnnouncement.id}`, this.form)
        } else {
          response = await axios.post('/api/admin/announcements', this.form)
        }

        if (response.data && response.data.success) {
          ElMessage.success(response.data.message || '保存成功')
          this.closeDialog()
          await this.fetchAnnouncements()
        } else {
          ElMessage.error(response.data.message || '保存失败')
        }
      } catch (e) {
        console.error('保存公告失败', e)
        ElMessage.error('保存失败，请重试')
      }
    },
    async deleteAnnouncement(id) {
      try {
        await ElMessageBox.confirm('确定要删除这条公告吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const { data } = await axios.delete(`/api/admin/announcements/${id}`)
        if (data && data.success) {
          ElMessage.success('删除成功')
          await this.fetchAnnouncements()
        } else {
          ElMessage.error(data.message || '删除失败')
        }
      } catch (e) {
        if (e !== 'cancel') {
          console.error('删除公告失败', e)
          ElMessage.error('删除失败，请重试')
        }
      }
    }
  },
  mounted() {
    this.fetchAnnouncements()
  }
}
</script>

<style scoped>
.sidebar { position: fixed; left: 0; top: 0; width: 240px; height: 100vh; background: #fff; border-right: 1px solid #e5e7eb; overflow-y: auto; }
.main-content { margin-left: 240px; min-height: 100vh; }
.nav-item { display: flex; align-items: center; padding: 12px 20px; color: #6b7280; text-decoration: none; transition: all 0.2s; cursor: pointer; width: 100%; background: transparent; border: 0; text-align: left; }
.nav-item:hover { background: #f3f4f6; color: #3b82f6; }
.nav-item.active { background: #eff6ff; color: #3b82f6; font-weight: 500; }
.nav-item i { width: 20px; margin-right: 12px; }
.nav-section { padding: 16px 20px 8px; font-size: 12px; color: #9ca3af; font-weight: 500; text-transform: uppercase; letter-spacing: 0.5px; }
.content-card { background: white; border-radius: 12px; padding: 24px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
.announcement-card { background: white; border: 1px solid #e5e7eb; border-radius: 12px; padding: 20px; margin-bottom: 16px; transition: all 0.2s; cursor: pointer; }
.announcement-card:hover { box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); border-color: #3b82f6; }
.status-badge { display: inline-block; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 500; }
.status-published { background: #d1fae5; color: #065f46; }
.status-draft { background: #f3f4f6; color: #6b7280; }
.status-scheduled { background: #dbeafe; color: #1e40af; }
</style>

